package com.example.springboot_demo01.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.example.springboot_demo01.config.AliPayConfig;
import com.example.springboot_demo01.entity.Trade;
import com.example.springboot_demo01.service.TradeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RestController
@Api(tags="支付宝支付接口")
@RequestMapping("/alipay")
public class AliPayController
{

    @Resource
    TradeService tradeService;

    @GetMapping("/doPay")
    @ApiOperation("开始支付")
    public String doPay(){
        //1.创建一个AlipayClient对象 ---配置基本参数
        AlipayClient alipayClient = new DefaultAlipayClient(
                AliPayConfig.gatewayUrl,

                AliPayConfig.app_id,
                AliPayConfig.merchant_private_key, "json",
                AliPayConfig.charset,
                AliPayConfig.alipay_public_key,
                AliPayConfig.sign_type );

        //2.创建一个支付请求对象
        AlipayTradePagePayRequest aliPayRequest = new AlipayTradePagePayRequest();

        //3.设置支付完成的回调
        aliPayRequest.setNotifyUrl(AliPayConfig.notify_url);
        //aliPayRequest.setReturnUrl(AliPayConfig.return_url);


        //4.设置支付内容信息
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", UUID.randomUUID());   //商户订单号
        bizContent.put("total_amount", "11.12");  //付款金额
        bizContent.put("subject", "魏启明--支付测试单");           //订单名称
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");   //PC网页支付
        aliPayRequest.setBizContent(bizContent.toString());

        //5.发起请求
        String result = null;
        try {
            result = alipayClient.pageExecute(aliPayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return result;
    }
    @ApiOperation("支付宝支付成功的回调")
    @PostMapping("/notify")  //注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }
            System.out.println("交易名称: " + params.get("subject")+  "交易状态: " + params.get("trade_status"));
            System.out.println("支付宝交易凭证号: " + params.get("trade_no"+"商户订单号: ") + params.get("out_trade_no"));
            System.out.println("交易金额: " + params.get("total_amount"));
            //根据商户订单号 获得订单信息
            Trade  trade = tradeService.getByTradeNo(params.get("out_trade_no"));
            if(trade!=null){
                //设置该订单的状态为已经支付
                trade.setStatus(1);
                //保存修改
               int n =  tradeService.update(trade);
                System.out.println("订单修改:"+(n>0?"成功":"失败"));
            }
        }
        return "success";
    }


    @GetMapping("/tradePay")
    @ApiOperation("对某个订单发起支付")
    public String tradePay(int id){
        //根据id获得订单信息
        Trade trade = tradeService.getById(id);
        //判断该订单是否存在 且  未支付
        if(trade==null  || trade.getStatus()==1){
            return  "不存在该未支付的订单！";
        }

        AlipayClient alipayClient = new DefaultAlipayClient(
                AliPayConfig.gatewayUrl,
                AliPayConfig.app_id,
                AliPayConfig.merchant_private_key, "json",
                AliPayConfig.charset,
                AliPayConfig.alipay_public_key,
                AliPayConfig.sign_type );

        //2.创建一个支付请求对象
        AlipayTradePagePayRequest aliPayRequest = new AlipayTradePagePayRequest();

        //3.设置支付完成的回调
        aliPayRequest.setNotifyUrl(AliPayConfig.notify_url);
        //aliPayRequest.setReturnUrl(AliPayConfig.return_url);


        //4.设置支付内容信息
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", trade.getTradeNo());   //商户订单号
        bizContent.put("total_amount",trade.getTotalMoney());  //付款金额
        bizContent.put("subject", "魏启明--支付测试单");           //订单名称
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");   //PC网页支付
        aliPayRequest.setBizContent(bizContent.toString());

        //5.发起请求
        String result = null;
        try {
            result = alipayClient.pageExecute(aliPayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return result;

    }
}
